package com.by_man.presenter.module_health_management.measure_blood_sugar;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.module_gestureLock.GestureLockActivity;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.NetworkDataManager;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 查看所以血糖记录
 * Created by man on 2017-02-18.
 */
public class CheckBloodSugarActivity extends AppCompatActivity {
    private Handler handler;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_blood_sugar);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                initView();
            }
        };
        if (null == UserInfos.All_BloodSugar_Record) { // 开启线程
            progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("提示信息");
            progressDialog.setMessage("正在请求数据，请稍后......");
            progressDialog.setCancelable(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();
            if (NetworkDataManager.BSNum < 1) {  // 对此请求后，询问用户
                showRequestAgain();
            }
            Thread thread = new Thread() {
                public void run() {
                    while (null == UserInfos.All_BloodSugar_Record) {  // 阻塞等待数据的初始化
                        if (NetworkDataManager.BSNum< 1) {
                            showRequestAgain();
                        }
                    }
                    progressDialog.dismiss();
                    Message message = Message.obtain(handler);
                    message.sendToTarget();
                }
            };
            thread.setDaemon(true);             // 设置为守护线程
            thread.start();
        }
        else {
            initView();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(this, MeasureBloodSugarActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, MeasureBloodSugarActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode,event);
    }

    protected void onRestart()
    {
        super.onRestart();
        Intent intent=new Intent(this,GestureLockActivity.class);
        intent.putExtra("class",this.getClass().getName());
        intent.putExtra("position", 0);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        JSONArray jsonArray = LocalDataManager.getAllBloodSugarRecord();
        if (null != jsonArray) {
            ListView lv = (ListView)findViewById(R.id.list_record);
            ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String,Object>>();
            try {
                String json = jsonArray.toString();
                //将获得的数据分为前后两部分
                JSONObject temp, temp1, temp2;
                String[] a = new String[json.length() / 2];
                String[] b = new String[json.length() / 2];
                int m = jsonArray.length() / 2;
                for (int j = 0; j < jsonArray.length() / 2; j++) {
                    temp = (JSONObject) jsonArray.get(j);
                    temp1 = (JSONObject) jsonArray.get(j + m);
                    HashMap<String, Object> map = new HashMap<String, Object>();
//                                final String data_id = temp.getString("data_id");
//                                int i = Integer.valueOf(data_id).intValue();

                    String xtz = temp.getString("value");
                    String tag = temp1.getString("value");
                    String temptime = temp.getString("updated_at");
                    String date = temptime.substring(0, 10);
                    String time = temptime.substring(11, 16);
                    String tempType = temp.getString("type");
                    if (tempType.equalsIgnoreCase("null")) {
                        tempType = "未知";
                    } else if (tempType.equalsIgnoreCase("0")) {
                        tempType = "手动";
                    } else {
                        tempType = "蓝牙";
                    }
                    if (j > 0) {
                        //获取前一个时间判定是否相等
                        temp2 = (JSONObject) jsonArray.get(j - 1);
                        String temptime2 = temp2.getString("updated_at");
                        String date2 = temptime2.substring(0, 10);
                        if (date.equals(date2)) {
                            date = "";
                        }
                        a[j] = xtz;
                        b[j] = tag;

                        map.put("xt", a[j]);
                        map.put("tag", b[j]);
                        map.put("showdate", date);
                        map.put("showtime", time);
                        map.put("type", tempType);

                        listItem.add(map);

                        SimpleAdapter adapter;

                        adapter = new SimpleAdapter(CheckBloodSugarActivity.this, listItem, R.layout.check_bs_listview_item,
                                new String[]{"showdate", "showtime", "xt", "tag", "type"},
                                new int[]{R.id.showdate, R.id.showtime, R.id.blood_sugar, R.id.tag, R.id.type});
                        //list_jil.setVisibility(View.VISIBLE);
                        lv.setAdapter(adapter);
                    } else {
                        a[j] = xtz;
                        b[j] = tag;
                        map.put("xt", a[j]);
                        map.put("tag", b[j]);
                        map.put("showdate", date);
                        map.put("showtime", time);
                        map.put("type", tempType);
                        listItem.add(map);
                        SimpleAdapter adapter;
                        adapter = new SimpleAdapter(CheckBloodSugarActivity.this, listItem, R.layout.check_bs_listview_item,
                                new String[]{"showdate", "showtime", "xt", "tag", "type"},
                                new int[]{R.id.showdate, R.id.showtime, R.id.blood_sugar, R.id.tag, R.id.type});
                        lv.setAdapter(adapter);
                    }
                }
            }catch (JSONException je){
                je.printStackTrace();
            }
        }

    }

    public void showRequestAgain() {
        android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this).setTitle("提醒")
                .setMessage("已多次请求服务器，是否继续请求？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        NetworkDataManager.BSNum = 3;
                        LocalDataManager.getAllBloodSugarRecord();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create();
        alertDialog.show();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
